<?php
/*
 * @Author: your name
 * @Date: 2021-05-20 10:19:39
 * @LastEditTime: 2021-06-29 16:07:10
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \myframe\app\Http\Controllers\Admin\LoginController.php
 */
namespace App\Http\Controllers\Admin;

use App\Category;
use App\Article;

class CategoryController extends CommonController
{
    //栏目列表查询
    public function index(Category $category)
    {
        $data = $category->orderBy('sort', 'asc')->get();
        $this->assign('category', $data);
        return $this->fetch('admin/category_list');
    }

    //栏目列表删除
    public function delete(Category $category, Article $article)
    {
        $id =$this->request->get('id');
        if ($category->where('id', $id)->delete()) {
            $this->success('删除成功！！');
        }
        //将删除栏目下的文章也同时 删除(将)
        $article->where('cid', $id)->update(['cid'=>0]);
    }

    // 查询 单条栏目 信息
    public function edit(Category $category)
    {
        $id =$this->request->get('id');
        if ($id) {
            $data =$category->where('id', $id)->first();
            if (!$data) {
                return '栏目不存在！';
            } else {
                $data=['name'=>$data['name'],'sort'=>$data['sort']];
                // $data=['name'=>'','sort'=>'0'];
            }
        }
        $this->assign('id', $id);
        $this->assign('data', $data);
        return $this->fetch('admin/category_edit');
    }

    //保存修改信息 或者 添加栏目信息
    public function save(Category $category)
    {
        $id = $this->request->post('id');
        $data = [
            'name' => $this->request->post('name', ''),
            'sort' => $this->request->post('sort', 0)
        ];
        if ($id) {
            $category->where('id', $id)->update($data);
            $this->success('修改完成。');
        } else {
            $category->insert($data);
            $this->success('添加完成。');
        }
    }
}
